package com.hl.shifangzhiyu.service.Impl;
import com.hl.shifangzhiyu.mapper.UserMapper;
import com.hl.shifangzhiyu.pojo.User;
import com.hl.shifangzhiyu.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Override
   public User login(String phone, String password) {
       User user = userMapper.findByPhone(phone);
       if (user != null && user.getPassword().equals(password)) {
           return user;
       }
       return null;
    }

    public boolean  register(User user) {
        System.out.println("1"+user);
       if (userMapper.findByPhone(user.getPhone())!= null){
           return false;
       }
       user.setPassword(md5(user.getPassword()));
       user.setPoints(0);
       return userMapper.insert(user) > 0;
   }
    @Override
    public boolean updateUser(User user) {
        return userMapper.updateUser(user) > 0;
    }

    @Override
    public User getById(Integer id) {
        return userMapper.getUserById(id);
    }
    @Override
    public boolean changePassword(Integer userId, String oldPassword, String newPassword) {
        User user = userMapper.selectById(userId);
        if (user == null) return false;

        String oldMd5 = DigestUtils.md5DigestAsHex(oldPassword.getBytes());
        if (!oldMd5.equals(user.getPassword())) {
            return false; // 原密码不匹配
        }

        String newMd5 = DigestUtils.md5DigestAsHex(newPassword.getBytes());
        user.setPassword(newMd5);
        return userMapper.updatePassword(userId, newMd5) > 0;
    }

    public String md5(String plainText) {
        return DigestUtils.md5DigestAsHex(plainText.getBytes());
    }


}
